<template>
  <div class="white-bg commonBoxmp">
    <TableV2
      class="flex1"
      :data="state.tableData"
      ref="tableV2Ref"
      selection
      @selectionChange="handleSelectionChange"
      :columns="state.columnData"
    >
      <template #tableHeader>
        <div class="jcb aic w100">
          <el-form ref="queryForm" size="small" :inline="true">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input
                v-model="state.form.nickName"
                clearable
                disabled
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item label="登录账号" prop="userName">
              <el-input
                v-model="state.form.userName"
                placeholder="请输入手机号码"
                clearable
                disabled
                style="width: 240px"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="aic jcc mt20">
          <el-button type="primary" @click="submitForm()">授权</el-button>
        </div>
      </template>
    </TableV2>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import Column from "/@ts/components/table/Column";
import selectDict from "/@/components/selectDict/index.vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import formatTool from "/@ts/hooks/format";
import { getAuthRole, updateAuthRole } from "/@ts/axios/urlApi/system/user";
import { authUserCancel } from "/@ts/axios/urlApi/system/role";

const router = useRouter();
const route = useRoute();
const { parseTime, addDateRange } = formatTool();
/*
基本数据类型
引用数据类型（复杂类型） 个人建议 ref初始化变量 
ref 和 reactive 本质我们可以简单的理解为ref是对reactive的二次包装, 
ref定义的数据访问的时候要多一个.value
*/
const dialogVisible = ref(true);
const state: any = reactive({
  openDataScope: false,
  defaultProps: {
    children: "children",
    label: "label",
  },
  menuOptions: [],
  deptOptions: [],

  deptExpand: false,
  deptNodeAll: false,
  menuExpand: false,
  menuNodeAll: false,
  // 表格基础配置 start
  title: "",
  form: {},
  userVisible: false,
  roleIds: [],
  height: 0,
  tableData: [],
  columnData: [
    {
      label: "角色编号",
      prop: "roleId",
      visible: true,
    },
    {
      label: "角色名称",
      prop: "roleName",
      visible: true,
    },
    {
      label: "权限字符",
      prop: "roleKey",
      visible: true,
    },

    {
      label: "创建时间",
      prop: "createTime",
      visible: true,
    },
  ],
  loading: false,
  // 表格基础配置 end
});
// 表格基础配置 start

const queryFormInit = {
  pageNum: 1,
  pageSize: 10,
  userName: "",
  phonenumber: "",
};
const queryParams = reactive(JSON.parse(JSON.stringify(queryFormInit)));
const getCurrentColumns = (data: Column[]) => {
  state.columnData = data;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  // 将对象的属性复制为初始值
  Object.assign(queryParams, queryFormInit);
  handleQuery();
};
const handleSelectionChange = (selection: any) => {
  state.roleIds = selection.map((item: any) => item.roleId);
};
const submitForm = async (formEl: FormInstance | undefined) => {
  const userId = queryParams.userId;
  const roleIds = state.roleIds.join(",");
  updateAuthRole({ userId: userId, roleIds: roleIds }).then(
    (response: ResponseConfig) => {
      ElMessage.success("授权成功");
      close();
    },
  );
};
/** 修改按钮操作 */
const cancelAuthUser = (row: any) => {
  const roleId = queryParams.roleId;
  ElMessageBox.confirm('确认要取消该用户"' + row.roleName + '"角色吗？')
    .then(function () {
      return authUserCancel({ userId: row.userId, roleId: queryParams.userId });
    })
    .then(() => {
      ElMessage.success("取消授权成功");
    })
    .catch(function () {});
};

// 表格基础配置 end
const tableV2Ref = ref();
//查询用户列表
const getList = () => {
  state.loading = true;
  getAuthRole(queryParams.userId).then((response: ResponseConfig) => {
    state.form = response.user;
    state.tableData = response.roles;
    state.loading = false;
    nextTick(() => {
      state.tableData.forEach((row: any) => {
        if (row.flag) {
          tableV2Ref.value.tableRef.toggleRowSelection(row);
        }
      });
    });
  });
};

// 树权限（父子联动）
const close = () => {
  router.go(-1);
};

onMounted(() => {
  const userId: any = route.params && route.params.userId;
  if (userId) {
    queryParams.userId = userId;
    getList();
  }
});
</script>

<style scoped lang="scss"></style>
